package com.catazy.wanandroid.ndkdemo

import android.content.Context
import android.graphics.BitmapFactory
import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.RadioButton
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.catazy.wanandroid.ndkdemo.databinding.ActivityMainBinding
import com.catazy.wanandroid.ndkdemo.databinding.SampleSelectedLayoutBinding
import java.io.InputStream
import java.nio.ByteBuffer
import java.util.Arrays

class MainActivity : AppCompatActivity() {

    companion object {
        const val SAMPLE_TYPE = 200
        const val SAMPLE_TYPE_KEY_TRIANGLE = 0
        const val SAMPLE_TYPE_KEY_TEXTURE_MAP = 1
        const val SAMPLE_TYPE_KEY_YUV_TEXTURE_MAP = 2
        const val SAMPLE_TYPE_KEY_VAO = 3

        val SAMPLE_TITLES = arrayOf(
            "绘制三角形", "纹理映射", "绘制YUV图", "VAO&VBO"
        )
    }

    private lateinit var binding: ActivityMainBinding

    private var mSampleSelectedIndex = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        // 初始化GLSurfaceView
        binding.glSurfaceView.getNativeRender().native_OnInit()

        loadNV21Image()
    }

    override fun onDestroy() {
        super.onDestroy()
        // 释放资源
        binding.glSurfaceView.getNativeRender().native_OnUnInit()
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu_main, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.action_change_sample -> {
                showGLSampleDialog()
            }

        }
        return true
    }

    /**
     * 加载RGBA格式的图片
     */
    private fun loadRGBAImage() {
        val inputStream = resources.openRawResource(R.raw.dzzz)
        try {
            val bitmap = BitmapFactory.decodeStream(inputStream)
            bitmap?.let {
                // 获取bitmap的字节大小
                val byteCount = it.byteCount
                // 分配新的字节缓冲区
                val byteBuffer = ByteBuffer.allocate(byteCount)
                // 将bitmap的像素复制到byteBuffer中
                it.copyPixelsToBuffer(byteBuffer)
                // 设置图像数据
                binding.glSurfaceView.getNativeRender().native_SetImageData(
                    MyGLSurfaceView.IMAGE_FORMAT_RGBA,
                    it.width,
                    it.height,
                    byteBuffer.array()
                )
            }
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            inputStream.close()
        }
    }

    /**
     * 加载NV21格式的图片
     */
    private fun loadNV21Image() {
        var inputStream: InputStream? = null
        try {
            inputStream = assets.open("YUV_Image_840x1074.NV21")
            // 输入流长度
            var length = inputStream.available()
            // 新建字节数组
            val buffer = ByteArray(length)
            // 输入流内容读入字节数组
            inputStream.read(buffer)

            binding.glSurfaceView.getNativeRender()
                .native_SetImageData(
                    MyGLSurfaceView.IMAGE_FORMAT_NV21,
                    840,
                    1074,
                    buffer
                )
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            inputStream?.close()
        }
    }

    private fun showGLSampleDialog() {
        val dialog = AlertDialog.Builder(this).create()
        val rootBinding = SampleSelectedLayoutBinding.inflate(layoutInflater)
        rootBinding.confirmBtn.setOnClickListener {
            dialog.cancel()
        }

        val adapter = MyRecyclerViewAdapter(this, SAMPLE_TITLES.asList())
        adapter.selectIndex = mSampleSelectedIndex
        adapter.addOnItemClickListener(object : MyRecyclerViewAdapter.OnItemClickListener {
            override fun onItemClick(view: View?, position: Int) {
                val selectIndex = adapter.selectIndex
                adapter.selectIndex = position
                adapter.notifyItemChanged(selectIndex)
                adapter.notifyItemChanged(position)
                mSampleSelectedIndex = position

                binding.glSurfaceView.getNativeRender().native_SetParamsInt(SAMPLE_TYPE, position)

                when (position) {
                    SAMPLE_TYPE_KEY_TRIANGLE -> {}
                    SAMPLE_TYPE_KEY_TEXTURE_MAP -> {
                        loadRGBAImage()
                    }

                    SAMPLE_TYPE_KEY_YUV_TEXTURE_MAP -> {
                        loadNV21Image()
                    }
                }

                binding.glSurfaceView.requestRender()

                dialog.cancel()
            }

        })

        val linearLayoutManager = LinearLayoutManager(this)
        linearLayoutManager.orientation = LinearLayoutManager.VERTICAL
        rootBinding.resolutionListView.layoutManager = linearLayoutManager
        rootBinding.resolutionListView.adapter = adapter

        dialog.show()
        dialog.window?.setContentView(rootBinding.root)
    }


    class MyRecyclerViewAdapter(private val mContext: Context, private val mTitles: List<String>) :
        RecyclerView.Adapter<MyRecyclerViewAdapter.MyViewHolder?>(), View.OnClickListener {
        var selectIndex = 0
        private var mOnItemClickListener: OnItemClickListener? = null

        fun addOnItemClickListener(onItemClickListener: OnItemClickListener?) {
            mOnItemClickListener = onItemClickListener
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
            val view = LayoutInflater.from(parent.context)
                .inflate(R.layout.sample_item_layout, parent, false)
            val myViewHolder: MyViewHolder = MyViewHolder(view)
            view.setOnClickListener(this)
            return myViewHolder
        }

        override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
            holder.mTitle.text = mTitles[position]
            if (position == selectIndex) {
                holder.mRadioButton.setChecked(true)
                holder.mTitle.setTextColor(mContext.resources.getColor(R.color.colorAccent))
            } else {
                holder.mRadioButton.setChecked(false)
                holder.mTitle.text = mTitles[position]
                holder.mTitle.setTextColor(Color.GRAY)
            }
            holder.itemView.tag = position
        }

        override fun getItemCount(): Int {
            return mTitles.size
        }

        override fun onClick(v: View) {
            if (mOnItemClickListener != null) {
                mOnItemClickListener!!.onItemClick(v, v.tag as Int)
            }
        }

        interface OnItemClickListener {
            fun onItemClick(view: View?, position: Int)
        }

        inner class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            var mRadioButton: RadioButton
            var mTitle: TextView

            init {
                mRadioButton = itemView.findViewById(R.id.radio_btn)
                mTitle = itemView.findViewById(R.id.item_title)
            }
        }
    }


}